package com.bbs.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbs.dto.Archive;
import com.bbs.dto.SearchResult;
import com.bbs.feign.SearchClient;
import com.bbs.mapper.PostMapper;
import com.bbs.pojo.Post;
import com.bbs.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private SearchClient searchClient;
    @Autowired
    private PostMapper postMapper;

    @Override
    public IPage<Post> searchPosts(String text, Long pageNo, Long pageSize) {
        SearchResult searchResult = searchClient.searchArchive(text, pageNo, pageSize);
        List<Archive> archives = searchResult.getArchives();

        //从appendix里拿到postId查询
        List<String> postIds = new ArrayList<>();
        for (Archive archive : archives) {
            postIds.add(archive.getAppendix());
        }
        List<Post> posts = null;
        if(postIds.isEmpty()){
            posts = new ArrayList<>();
        }else{
            posts = postMapper.selectBatchIds(postIds);
        }

        IPage<Post> postPage = new Page<>();
        postPage.setCurrent(pageNo);
        postPage.setRecords(posts);
        postPage.setSize(pageSize);
        postPage.setTotal(searchResult.getItemCount());

        return postPage;
    }

    @Override
    public void savePost(Post post) {
        try{
            Archive archive = new Archive();
            //标题和内容参与搜索
            archive.setContent(post.getTitle() + " " + post.getContent());
            //附带上帖子id
            archive.setAppendix(post.getPostId());
            searchClient.addArchive(archive);
        }catch (Throwable e){
            //TODO: 服务降级
            //拦截所有异常，避免对帖子插入的阻碍
            e.printStackTrace();
        }
    }


    @Override
    public void deletePost(String postId) {
        try{
            searchClient.deleteArchiveByAppendix(postId);
        }catch (Throwable e){
            //TODO: 服务降级
            e.printStackTrace();
        }
    }
}
